package com.study.design.pattern.pattern.behavioral.Iterator;

import java.util.*;

/**
 * @Author: gongsl
 * @Date: 2025-03-23 11:42
 * @description: 书架类(即自定义集合类)
 */
public class BookShelf implements Iterable<Book> {
    private List<Book> books = new ArrayList<>();

    /**
     * 添加书籍
     */
    public void addBook(Book book) {
        books.add(book);
    }

    /**
     * 核心：实现迭代器
     */
    @Override
    public Iterator<Book> iterator() {
        return new BookIterator();
    }

    /**
     * 内部迭代器类
     */
    private class BookIterator implements Iterator<Book> {
        /**
         * 当前遍历位置
         */
        private int cursor = 0;

        @Override
        public boolean hasNext() {
            return cursor < books.size();
        }

        @Override
        public Book next() {
            if (!hasNext()) throw new NoSuchElementException();
            /**
             * 返回当前元素，游标后移
             */
            return books.get(cursor++);
        }
    }
}
